package com.khotyn.heresy.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.khotyn.heresy.bean.Friend;
import com.khotyn.heresy.bean.HeresyErrorMessage;
import com.khotyn.heresy.bean.UserDetail;
import com.khotyn.heresy.dao.FriendDAO;
import com.khotyn.heresy.exception.IllegalUrlParamException;
import com.khotyn.heresy.service.UserService;

/**
 * 用户中心控制器
 * 
 * @author 黄挺
 * 
 */
@Controller
@RequestMapping("/user.html")
public class UserController {
	@Autowired
	private UserService userService;

	@Autowired
	private FriendDAO friendDAO;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView onLoad(HttpSession session, HttpServletRequest request, ModelMap model,
			@RequestParam(value = "userID", required = false) String userIDStr) {
		Integer myID = (Integer) session.getAttribute("userID");
		HeresyErrorMessage message = null;
		UserDetail user = null;

		try {
			validate(userIDStr);
		} catch (IllegalUrlParamException e) {
			return e.getErrorModel();
		}

		Integer userID = Integer.parseInt(userIDStr);

		// 是否为好友
		Friend friend = friendDAO.selectOneFriend(myID, userID);

		if (friend != null)
			model.addAttribute("isFriend", true);
		else
			model.addAttribute("isFriend", false);

		try {
			user = userService.doService(userID);
		} catch (Exception e) {
			// 不存在的用户或者是未登录的用户
			e.printStackTrace();
			message = new HeresyErrorMessage(e.getMessage(), "操作失败", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		}

		return new ModelAndView("user", "user", user);
	}

	private void validate(String userIDStr) throws IllegalUrlParamException {
		HeresyErrorMessage message = null;

		if (!NumberUtils.isDigits(userIDStr)) {
			message = new HeresyErrorMessage("非法的参数", "操作失败", "login.html");
		}

		if (message != null) {
			throw new IllegalUrlParamException(message);
		}

	}
}
